'use strict';

/**
 * @ngdoc directive
 * @name jgappApp.directive:contenteditable
 * @description
 * # contenteditable
 */
angular.module('jgappApp').
  directive('contenteditable', ['$sce', function ($sce) {
    return {
      restrict: 'AE', // only activate on element attribute
      require: '?ngModel', // get a hold of NgModelController
      link: function (scope, element, attrs, ngModel) {
        if (!ngModel) return; // do nothing if no ng-model
        var el = element[0];

        // Specify how UI should be updated
        ngModel.$render = function () {
          element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
        };
        // Listen for change events to enable binding
        element.on('keyup change', function () {
          scope.$evalAsync(read);
        });

        // function getCaretCharacterOffsetWithin(element) {
        //   var caretOffset = 0;
        //   var doc = element.ownerDocument || element.document;
        //   var win = doc.defaultView || doc.parentWindow;
        //   var sel;
        //   if (typeof win.getSelection != "undefined") {
        //     sel = win.getSelection();
        //     if (sel.rangeCount > 0) {
        //       var range = win.getSelection().getRangeAt(0);
        //       var preCaretRange = range.cloneRange();
        //       preCaretRange.selectNodeContents(element);
        //       preCaretRange.setEnd(range.endContainer, range.endOffset);
        //       caretOffset = preCaretRange.toString().length;
        //     }
        //   } else if ((sel = doc.selection) && sel.type != "Control") {
        //     var textRange = sel.createRange();
        //     var preCaretTextRange = doc.body.createTextRange();
        //     preCaretTextRange.moveToElementText(element);
        //     preCaretTextRange.setEndPoint("EndToEnd", textRange);
        //     caretOffset = preCaretTextRange.text.length;
        //   }
        //   return caretOffset;
        // }
        read(); // initialize
        // Write data to the model
        function read() {
          var html = element.html();
          // When we clear the content editable the browser leaves a <br> behind
          // If strip-br attribute is provided then we strip this out
          if (attrs.stripBr && html == '<br>') {
            html = '';
          }

          // console.log(getCaretCharacterOffsetWithin(el))
          ngModel.$setViewValue(html);
        }
      }
    };
  }]);
